﻿using System;
using System.Web.UI.WebControls;

namespace ECommerce.Administration.Controls
{
	public partial class NewsList : AdminBaseUsercontrol
	{
		private Service.INewsService _NewsService;

		protected void Page_Load(object sender, EventArgs e)
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~Administration/AdminLogin.aspx");
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindData();
		}

		protected void GridNews_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
		{
			if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.Header)
			{
				e.Row.Cells[1].Text = GetLocalResourceString("Admin.NewsList.TitleHeader");
				e.Row.Cells[2].Text = GetLocalResourceString("Admin.NewsList.ShortContentHeader");
				e.Row.Cells[3].Text = GetLocalResourceString("Admin.NewsList.CreatedOnHeader");
				e.Row.Cells[4].Text = GetLocalResourceString("Admin.NewsList.PublishedHeader");
				e.Row.Cells[5].Text = GetLocalResourceString("Admin.NewsList.AllowCommentsHeader");
			}

			if (e.Row.DataItem != null)
			{
				var HyperLinkNewsTitle = e.Row.FindControl("HyperLinkNewsTitle") as HyperLink;
				var data = e.Row.DataItem as Data.Entity.News;

				HyperLinkNewsTitle.Text = data.Title;
				HyperLinkNewsTitle.NavigateUrl = "~/Administration/EditNews.aspx?newsid=" + data.NewsID.ToString();
			}
		}

		private void BindData()
		{
			if (_NewsService == null)
			{
				_NewsService = new Service.NewsService();
			}

			var languageID = 0;

			if (SiteContext.Current.WorkingLanguage != null)
			{
				languageID = SiteContext.Current.WorkingLanguage.LanguageId;

				var news = _NewsService.GetAllNewsByLanguage(languageID);

				GridNews.DataSource = news;
				GridNews.DataBind();
			}
		}

		public void DeleteSelectedNews()
		{
			if (_NewsService == null)
			{
				_NewsService = new Service.NewsService();
			}

			foreach (System.Web.UI.WebControls.GridViewRow rowItem in GridNews.Rows)
			{
				var chBox = rowItem.FindControl("cbNews") as CheckBox;
				var hfNewsID = rowItem.FindControl("hfNewsId") as HiddenField;

				bool isChecked = chBox.Checked;
				int newsID = int.Parse(hfNewsID.Value);

				if (isChecked)
				{
					_NewsService.DeleteNews(newsID);
				}
			}

			BindData();
		}
	}
}